package com.xxl.sso.core.login;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.xxl.sso.core.conf.Conf;
import com.xxl.sso.core.user.XxlSsoUser;

/**
 * @author xuxueli 2018-04-03
 */
public class SsoWebLoginHelper {

    /**
     * client login
     *
     * @param response
     * @param sessionId
     * @param ifRemember    true: cookie not expire, false: expire when browser close （server cookie）
     * @param xxlUser
     */
    public static String login(HttpServletRequest request, HttpServletResponse response, String userId, String username, boolean ifRemember) {
        String accessToken = SsoTokenLoginHelper.login(userId, username);

        HttpSession session = request.getSession();
        session.setAttribute(Conf.SSO_SESSION_ACCESS_TOKEN, accessToken);
        int age = ifRemember ? 60 * 60 * 24 * 15 : 60 * 60 * 12; // 如果记住密码则15天内免登录，否则12小时自动登出
        session.setMaxInactiveInterval(age); // 过期时间， 单位为秒 设置为-1永不过期

        return accessToken;
    }

    /**
     * login check
     *
     * @param request
     * @param response
     * @return
     */
    public static XxlSsoUser loginCheck(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        String accessToken = (String) session.getAttribute(Conf.SSO_SESSION_ACCESS_TOKEN);

        // cookie user
        XxlSsoUser xxlUser = SsoTokenLoginHelper.loginCheckByAccessToken(accessToken);
        if (xxlUser != null) {
            return xxlUser;
        }

        // remove old cookie
        session.removeAttribute(Conf.SSO_SESSION_ACCESS_TOKEN);
        return null;
    }

    public static XxlSsoUser loginCheckByUserId(String userId, HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();

        XxlSsoUser xxlUser = SsoTokenLoginHelper.loginCheckByUserId(userId);
        if (xxlUser != null) {
            session.setAttribute(Conf.SSO_SESSION_ACCESS_TOKEN, xxlUser.getAccessToken());
            return xxlUser;
        }

        return null;
    }
}
